﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Xww.IO {
    public static class FileReaderWriter {

        #region Reader
        /// <summary>
        /// 逐行返回指定文件的所有行（实行延时加载，可读取超大文件）
        /// </summary>
        /// <returns>返回公开枚举器，应用 foreach 语句访问</returns>
        public static IEnumerable<string> ReadAllLines(this string fileName) {
            string line = null;
            using (StreamReader reader = new StreamReader(fileName)) {
                while ((line = reader.ReadLine()) != null) {
                    yield return line;
                }
            }
        }
        /// <summary>
        /// 逐行返回指定文件的所有行（实行延时加载，可读取超大文件）
        /// </summary>
        /// <returns>返回公开枚举器，应用 foreach 语句访问</returns>
        public static IEnumerable<string> ReadAllLines(this string fileName, Encoding encoding) {
            string line = null;
            using (StreamReader reader = new StreamReader(fileName, encoding)) {
                while ((line = reader.ReadLine()) != null) {
                    yield return line;
                }
            }
        }
        /// <summary>
        /// 返回指定文件包含的文本行数
        /// </summary>
        public static int GetLineCount(this string fileName) {
            return fileName.ReadAllLines().Count();
        } 
        #endregion

        #region Writer
        /// <summary>
        /// 用自动管理streamwriter的方式写入文件
        /// </summary>
        public static void WriteFileAction(this string FileName, bool apend, Action<StreamWriter> WriteAction) {
            StreamWriter writer = new StreamWriter(FileName, apend);
            using (writer) {
                WriteAction.Invoke(writer);
            }
        }
        /// <summary>
        /// 用自动管理streamwriter的方式写入文件，默认覆盖新原文件（如果已存在）
        /// </summary>
        public static void WriteFileAction(this string FileName, Action<StreamWriter> WriteAction) {
            FileName.WriteFileAction(false, WriteAction);
        }
        /// <summary>
        /// 用自动管理streamwriter的方式写入文件，默认覆盖新原文件（如果已存在）
        /// </summary>
        public static void WriteFileAction(this string FileName, Action<StreamWriter> WriteAction, Encoding encoding) {
            FileName.WriteFileAction(false, WriteAction, encoding);
        }
        /// <summary>
        /// 用自动管理streamwriter的方式写入文件
        /// </summary>
        public static void WriteFileAction(this string FileName, bool apend, Action<StreamWriter> WriteAction, Encoding encoding) {
            StreamWriter writer = new StreamWriter(FileName, apend, encoding);
            using (writer) {
                WriteAction.Invoke(writer);
            }
        }
        #endregion

    }
}
